package 中等;

import javax.xml.transform.Result;

public class 两数相加2 {

    public static void main(String[] args) {
        ListNode listNode3= new ListNode(9);
        ListNode listNode2= new ListNode(6,listNode3);
        ListNode listNode1= new ListNode(3,listNode2);
        ListNode listNode= new ListNode(2,listNode1);//2345+3456
        //TreeNode listNode03= new TreeNode(6);
        ListNode listNode02= new ListNode(5);
        ListNode listNode01= new ListNode(4,listNode02);
        ListNode listNode0= new ListNode(3,listNode01);//3456
        System.out.println(addTwoNumbers(listNode,listNode0 ));

    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        ListNode cur = result;
        int carry = 0;
        int sum;
        while (l1!=null || l2 != null){
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            sum  = x+y+carry;
            carry = sum/10;
            sum = sum % 10;
            cur.next = new ListNode(sum);
            cur = cur.next;
            if (l1!=null){
                l1 = l1.next;
            }
            if (l2!=null){
                l2 = l2.next;
            }

        }
        if (carry!=0){
            cur.next = new ListNode(carry);
        }
        return result.next;




    }

    public static ListNode reverseListNode(ListNode listNode){
        ListNode nextNode;
        ListNode curNode = listNode;
        nextNode = curNode.next;
        curNode.next = null;
        ListNode tail = curNode;
        curNode = nextNode;
        while (curNode!=null){
            nextNode = curNode.next;
            curNode.next = tail;
            tail = curNode;
            curNode = nextNode;
        }
        return tail;

    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }

    @Override
    public String toString() {
        ListNode cur = this;
        while (cur != null){
            System.out.print(cur.val+"->");
            cur = cur.next;
        }
        return "";
    }
}
